<?php

namespace App\Http\Controllers;


use App\Models\Rbac\GuardUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;


/**
 * 用于测试的控制器
 * Class DemoController
 * @package App\Http\Controllers
 */
class DemoController extends Controller {

    public function demo(Request $request) {

        dump('ip', $request->ip());
        dump('clientIp', $request->getClientIp());
        dump('clientIps', $request->getClientIps());
        dump('agent',$request->userAgent());


        return responseSuccess();
    }

    function truncateHtml($html, $limit) {
        $dom = new DOMDocument();
        @$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));

        $body = $dom->getElementsByTagName('body')->item(0);
        $result = '';
        $length = 0;

        foreach ($body->childNodes as $node) {
            $nodeHtml = $dom->saveHTML($node);
            $textLength = mb_strlen(strip_tags($nodeHtml));

            if ($length + $textLength > $limit) {
                // 处理部分截断
                $remaining = $limit - $length;
                if ($remaining > 0) {
                    $textContent = $node->textContent;
                    $truncated = mb_substr($textContent, 0, $remaining);
                    $result .= $truncated . '...';
                }
                break;
            }

            $result .= $nodeHtml;
            $length += $textLength;
        }

        return $result;
    }

    public function uEditor(Request $request) {
        return view('demo.uEditor');
    }

    public function dropDown(Request $request) {
        return view('demo.dropDown');

    }


    public function tableSelect(Request $request) {
        if($request->ajax()){
            $records = GuardUser::where('name','like','%'.$request->input('name').'%')
                ->get(['name','id'])->toArray();
            return responseSuccess($records,count($records));
        }

        $titles = (new GuardUser())->getTableTitleSettings();
        //$records = AdminUser::take(10)->get(['name','id as value']);
        return view('demo.tableSelect',compact('titles'));
    }

    public function xmSelect(Request $request) {

        if($request->has('tree')){
            return view('demo.xmSelect.tree');
        }

        if($request->ajax()){
            $records = GuardUser::where('name','like','%'.$request->input('name').'%') ->get(['name','id as value']);
            return json_encode(['data'=>$records]);
        }

        $records = GuardUser::take(10)->get(['name','id as value']);
        return view('demo.xmSelect.base',compact('records'));
    }


    public function eleTree(Request $request) {
        $permission = new Depart();
        $records = $permission->where('parent_id',0)->with('treeList')->get()->toArray();
        $records = json_encode($records,JSON_UNESCAPED_UNICODE);
        return view('demo.eleTree',compact('records'));
    }

}
